//! RustCloud 主框架配置广播集成示例
//! 
//! 展示如何在 RustCloud 应用中使用配置广播功能

use rustcloud::prelude::*;
use std::collections::HashMap;

/// 展示基本的配置广播功能使用
pub async fn basic_config_broadcast_example() -> RustCloudResult<()> {
    // 创建带有配置广播功能的 RustCloud 应用
    let config = RustCloudBuilder::new("user-service")
        .with_port(8080)
        .with_version("1.0.0")
        .with_environment("production")
        // 🆕 启用配置广播功能
        .enable_config_broadcast()
        // 🆕 设置消息总线类型（memory、redis、kafka等）
        .with_config_broadcast_bus("memory")
        // 🆕 设置广播主题前缀
        .with_config_broadcast_topic_prefix("myapp.config.broadcast")
        // 🆕 设置关注的应用列表
        .with_interested_applications(vec![
            "user-service".to_string(),
            "order-service".to_string(),
            "payment-service".to_string(),
        ])
        // 🆕 启用自动重启功能
        .enable_auto_restart()
        .build()
        .await?;

    tracing::info!("🚀 RustCloud 应用已创建，配置广播功能已启用");
    tracing::info!("📊 配置详情: {:?}", config);

    Ok(())
}

/// 展示高级配置广播功能使用
pub async fn advanced_config_broadcast_example() -> RustCloudResult<()> {
    // 创建高级配置
    let mut config = RustCloudConfig::default();
    
    // 基本服务配置
    config.service.name = "config-server".to_string();
    config.service.version = "2.0.0".to_string();
    config.service.environment = "production".to_string();
    
    // 配置广播功能
    config.components.config_broadcast.enabled = true;
    config.components.config_broadcast.message_bus_type = "redis".to_string();
    config.components.config_broadcast.topic_prefix = "enterprise.config.events".to_string();
    
    // Redis 连接配置
    let mut redis_config = HashMap::new();
    redis_config.insert("host".to_string(), serde_json::Value::String("redis.example.com".to_string()));
    redis_config.insert("port".to_string(), serde_json::Value::Number(serde_json::Number::from(6379)));
    redis_config.insert("password".to_string(), serde_json::Value::String("secure_password".to_string()));
    redis_config.insert("db".to_string(), serde_json::Value::Number(serde_json::Number::from(0)));
    config.components.config_broadcast.connection_config = redis_config;
    
    // 配置监听器
    config.components.config_broadcast.listeners = vec![
        rustcloud::ConfigBroadcastListenerConfig {
            name: "logging_listener".to_string(),
            listener_type: "logging".to_string(),
            interested_applications: vec!["user-service".to_string(), "order-service".to_string()],
            config: HashMap::new(),
        },
        rustcloud::ConfigBroadcastListenerConfig {
            name: "restart_listener".to_string(),
            listener_type: "restart".to_string(),
            interested_applications: vec!["user-service".to_string()],
            config: {
                let mut restart_config = HashMap::new();
                restart_config.insert("graceful_shutdown_timeout".to_string(), 
                    serde_json::Value::Number(serde_json::Number::from(30)));
                restart_config
            },
        },
    ];
    
    // 自动重启配置
    config.components.config_broadcast.auto_restart.enabled = true;
    config.components.config_broadcast.auto_restart.restart_delay_seconds = 60;
    config.components.config_broadcast.auto_restart.max_restart_attempts = 5;
    config.components.config_broadcast.auto_restart.restart_interval_seconds = 600; // 10分钟
    
    // 从配置创建应用
    let app_config = RustCloudBuilder::from_config(config)
        .build()
        .await?;

    tracing::info!("🏢 企业级配置广播应用已创建");
    tracing::info!("🔧 配置详情: {:?}", app_config);

    Ok(())
}

/// 展示配置文件方式使用配置广播功能
pub async fn config_file_broadcast_example() -> RustCloudResult<()> {
    // 生成示例配置文件内容
    let config_content = r#"
[service]
name = "api-gateway"
version = "3.0.0"
environment = "staging"

[network]
port = 8080
health_port = 8081

[components.config_broadcast]
enabled = true
message_bus_type = "kafka"
topic_prefix = "microservices.config.events"
interested_applications = ["api-gateway", "user-service", "order-service", "notification-service"]

[components.config_broadcast.connection_config]
bootstrap_servers = "kafka.example.com:9092"
security_protocol = "SASL_SSL"
sasl_mechanism = "PLAIN"
sasl_username = "config_broadcast_user"
sasl_password = "secure_kafka_password"

[[components.config_broadcast.listeners]]
name = "audit_listener"
listener_type = "logging"
interested_applications = ["api-gateway", "user-service"]

[[components.config_broadcast.listeners]]
name = "notification_listener"
listener_type = "custom"
interested_applications = ["notification-service"]

[components.config_broadcast.listeners.config]
webhook_url = "https://notifications.example.com/config-changes"
retry_attempts = 3
timeout_seconds = 10

[components.config_broadcast.auto_restart]
enabled = true
restart_delay_seconds = 45
max_restart_attempts = 3
restart_interval_seconds = 900
"#;

    // 保存配置到临时文件
    let config_path = "/tmp/rustcloud_broadcast_example.toml";
    tokio::fs::write(config_path, config_content).await
        .map_err(|e| RustCloudError::ConfigurationError(format!("写入配置文件失败: {}", e)))?;

    // 从配置文件创建应用
    let app_config = RustCloudBuilder::from_config_file(config_path)
        .await?
        .build()
        .await?;

    tracing::info!("📄 从配置文件创建的应用已就绪");
    tracing::info!("🎛️ 配置广播功能: {}", app_config.components.config_broadcast.enabled);
    tracing::info!("🚌 消息总线类型: {}", app_config.components.config_broadcast.message_bus_type);
    tracing::info!("📢 主题前缀: {}", app_config.components.config_broadcast.topic_prefix);

    // 清理临时文件
    let _ = tokio::fs::remove_file(config_path).await;

    Ok(())
}

/// 主要示例运行函数
pub async fn run_all_examples() -> RustCloudResult<()> {
    // 初始化日志
    tracing_subscriber::init();

    tracing::info!("🚀 开始运行 RustCloud 配置广播功能示例");

    // 运行基本示例
    tracing::info!("\n=== 基本配置广播示例 ===");
    basic_config_broadcast_example().await?;

    // 运行高级示例
    tracing::info!("\n=== 高级配置广播示例 ===");
    advanced_config_broadcast_example().await?;

    // 运行配置文件示例
    tracing::info!("\n=== 配置文件广播示例 ===");
    config_file_broadcast_example().await?;

    tracing::info!("✅ 所有配置广播示例运行完成");

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_config_broadcast_builder() {
        let config = RustCloudBuilder::new("test-service")
            .enable_config_broadcast()
            .with_config_broadcast_bus("memory")
            .with_config_broadcast_topic_prefix("test.config.broadcast")
            .with_interested_applications(vec!["test-service".to_string()])
            .enable_auto_restart()
            .build()
            .await
            .unwrap();

        assert!(config.components.config_broadcast.enabled);
        assert_eq!(config.components.config_broadcast.message_bus_type, "memory");
        assert_eq!(config.components.config_broadcast.topic_prefix, "test.config.broadcast");
        assert_eq!(config.components.config_broadcast.interested_applications, vec!["test-service"]);
        assert!(config.components.config_broadcast.auto_restart.enabled);
    }

    #[tokio::test]
    async fn test_config_broadcast_validation() {
        // 测试配置验证
        let config = RustCloudBuilder::new("validation-test")
            .enable_config_broadcast()
            .build()
            .await
            .unwrap();

        // 验证默认配置
        assert!(config.components.config_broadcast.enabled);
        assert_eq!(config.components.config_broadcast.message_bus_type, "memory");
        assert_eq!(config.components.config_broadcast.topic_prefix, "config.broadcast");
        assert!(config.components.config_broadcast.interested_applications.is_empty());
    }

    #[tokio::test]
    async fn test_config_from_file_with_broadcast() {
        // 创建临时配置文件
        let config_content = r#"
[service]
name = "test-from-file"
version = "1.0.0"

[components.config_broadcast]
enabled = true
message_bus_type = "redis"
topic_prefix = "test.config.events"
interested_applications = ["test-service"]

[components.config_broadcast.auto_restart]
enabled = true
restart_delay_seconds = 30
"#;

        let config_path = "/tmp/test_config_broadcast.toml";
        tokio::fs::write(config_path, config_content).await.unwrap();

        let config = RustCloudBuilder::from_config_file(config_path)
            .await
            .unwrap()
            .build()
            .await
            .unwrap();

        assert_eq!(config.service.name, "test-from-file");
        assert!(config.components.config_broadcast.enabled);
        assert_eq!(config.components.config_broadcast.message_bus_type, "redis");
        assert_eq!(config.components.config_broadcast.topic_prefix, "test.config.events");
        assert!(config.components.config_broadcast.auto_restart.enabled);
        assert_eq!(config.components.config_broadcast.auto_restart.restart_delay_seconds, 30);

        // 清理
        let _ = tokio::fs::remove_file(config_path).await;
    }
}

// 运行示例的便捷函数
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    run_all_examples().await?;
    Ok(())
}